var express = require("express");
var router = express.Router();
const { getAll, exec } = require("../db/index");

router.get("/", async (req, res) => {
  // 操作数据库
  let sql = `select * from user order by id desc`;
  const data = await getAll(sql);
  res.send({
    code: 0,
    message: "获取所有用户成功",
    data: data,
  });
});
router.post("/", async (req, res) => {
  const { username, password, usertype } = req.body;
  let sql = `insert into user (username,password,usertype) values ('${username}','${password}','${usertype}'`;
  const data = await exec(sql);
  res.send({
    code: 0,
    message: "添加用户成功",
    data: data,
  });
});
router.put("/", async (req, res) => {
  // const id = req.params.id;
  const { id, usertype } = req.body;
  let sql = `update user set usertype='${usertype}' where id = ${id}`;
  const data = await exec(sql);
  res.send({
    code: 0,
    message: "修改用户信息成功",
    data: data,
  });
});
router.delete("/username", async (req, res) => {
  // const id = req.params.id;
  const { username } = req.body;
  console.log(username)
  let sql = `delete from user where username ='${username}' `;
  const data = await exec(sql);
  res.send({
    code: 0,
    message: "删除用户成功",
    data: data,
  });
});
router.delete("/:id", async (req, res) => {
  const id = req.params.id;
  let sql = `delete from user where id ='${id}' `;
  const data = await exec(sql);
  res.send({
    code: 0,
    message: "删除用户成功",
    data: data,
  });
});
module.exports = router;